package com.cxy.service.Impl;

import com.cxy.Exception.TaskStatusException;
import com.cxy.dto.*;
import com.cxy.entity.Information;
import com.cxy.entity.Record;
import com.cxy.entity.Task;
import com.cxy.mapper.InformationMapper;
import com.cxy.mapper.RecordMapper;
import com.cxy.mapper.TaskMapper;
import com.cxy.mapper.UserMapper;
import com.cxy.service.TaskService;
import com.cxy.vo.TaskCompleteVO;
import com.cxy.vo.TaskNoRelease;
import com.cxy.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private InformationMapper informationMapper;
    @Autowired
    private UserMapper userMapper;
    /**
     * 添加任务
     * @param taskInsertDTO
     */
    public void insert(TaskInsertDTO taskInsertDTO) {
        //创建时间
        taskInsertDTO.setCreateTime(LocalDate.now());
        //创建人
        taskInsertDTO.setCreateUser("孙金");

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy'年'MM'月'");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

        try {
            //将原始字符串转换为date类型
            Date date = sdf1.parse(taskInsertDTO.getDateNumber());
            //将date类型转换为目标格式的字符串
            String dateNumber = sdf2.format(date);
            taskInsertDTO.setDateNumber(dateNumber);
            taskMapper.insert(taskInsertDTO);
        } catch (ParseException e) {
            e.printStackTrace();
        }

//        //获取task的主键值
//        Long taskId = taskInsertDTO.getId();
//        //在用户表中把与任务表关联的字段设置好
//        AllMessageDTO user = new AllMessageDTO();
//        List<UserVO> userVOS = userMapper.select();
//        for (UserVO userVO : userVOS) {
//            BeanUtils.copyProperties(userVO,user);
//            user.setTaskId(taskId);
//            userMapper.update(user);
//        }
    }

    /**
     * 查看任务（待发布）
     * @param seeTaskDTO
     * @return
     */
    public List<TaskNoRelease> seeTaskNoRelease(SeeTaskDTO seeTaskDTO) {
        List<TaskNoRelease>tasks=taskMapper.seeTaskNoRelease(seeTaskDTO);
        //创建集合存放taskNoRelease
        List<TaskNoRelease>list=new ArrayList<>();
       //遍历tasks把全部期数修改为yyyy年MM月形式
        for (TaskNoRelease task : tasks) {
             LocalDate date = LocalDate.parse(task.getDateNumber(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
             String dateNumber = date.format(DateTimeFormatter.ofPattern("yyyy年MM月"));
             task.setDateNumber(dateNumber);
             list.add(task);
        }
        return list;
    }

    /**
     * 修改任务期数
     * @param updateTaskDTO
     */
    public void updateTask(UpdateTaskDTO updateTaskDTO) {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy'年'MM'月'");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");

        try {
            //将原始字符串转换为date类型
            Date date = sdf1.parse(updateTaskDTO.getDateNumber());
            //将date类型转换为目标格式的字符串
            String dateNumber = sdf2.format(date);
            updateTaskDTO.setDateNumber(dateNumber);
            taskMapper.update(updateTaskDTO);
        } catch (ParseException e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据id查询任务期数
     * @return
     */
    public String getById(Long id) {
        Task task = taskMapper.getById(id);
        String dateNumber = task.getDateNumber();
        LocalDate date = LocalDate.parse(dateNumber);
        String result = date.format(DateTimeFormatter.ofPattern("yyyy年MM月"));

        return result;
    }

    /**
     * 发布任务
     * @param id
     */
    public void taskRelease(Long id) {
       //获取所有任务查询是否有正在进行的任务
        List<Task> tasks = taskMapper.selectAll();
        for (Task task : tasks) {
            if (task.getStatus().equals("2")){
                throw new TaskStatusException("有任务正在进行");
            }
        }
        Task taskId = taskMapper.getById(id);
        UpdateTaskDTO updateTaskDTO =new UpdateTaskDTO();
        BeanUtils.copyProperties(taskId,updateTaskDTO);
        updateTaskDTO.setStatus("2");
        taskMapper.update(updateTaskDTO);
      // 当发布一个新的任务时，需要新增所有用户并且需要把task_id设置当前新任务的id
        Information information =new Information();
        for (int i = 1; i <=3; i++) {
            information.setUserId((long) i);
            information.setTaskId(id);
            informationMapper.insert(information);
        }
        //并且生成评议项记录管理
        Record record = new Record();
        //先查询一共有多少个用户
        List<UserVO> users = userMapper.select();

        for (int i = 1; i <= users.size(); i++) {
            for (int j = 1; j <= users.size(); j++) {
                record.setTaskId(id);
                record.setUserId((long) i);
                record.setByReviewUserId((long) j);
                recordMapper.insert(record);
            }
        }
    }

    /**
     * 查询任务(进行中)
     * @param seeTaskDTO
     * @return
     */
    public TaskCompleteVO selectTaskComplete(SeeTaskDTO seeTaskDTO) {
        //前端传递任务正在进行中的状态
        Task task = taskMapper.selectTaskComplete(seeTaskDTO);
        LocalDate date = LocalDate.parse(task.getDateNumber(), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        String dateNumber = date.format(DateTimeFormatter.ofPattern("yyyy年MM月"));
        task.setDateNumber(dateNumber);
        TaskCompleteVO taskCompleteVO =new TaskCompleteVO();
        BeanUtils.copyProperties(task,taskCompleteVO);
        return taskCompleteVO;
    }

    /**
     * 删除任务
     * @param id
     */
    public void delete(Long id) {
        taskMapper.delete(id);
    }

    /**
     * 结束任务
     * @param id
     */
    public void overTask(Long id) {
        taskMapper.overTask(id);
    }
}
